/**
 * 面谈准备
 */
import React, { useState, useEffect, useMemo } from 'react';
import { router, withRouter } from 'umi';
import { Button, Form, message, Spin } from 'antd';

import { TitleControl } from '@/pages/Recruitment/components';
import { PageContainer } from '@/molecules';

import { defaultFormatResult, useRequest } from '@/hooks';
import { BottomAction } from '@/components';

import pageTabUtil from '@/utils/pageTabUtil';
import isEmpty from 'lodash/isEmpty';
import { CustomAdd } from '@/pages/Recruitment/containers';
import { ProfileCard } from '@/containers';
import { TalkArrange } from '../containers';
import { getTalKPrepare, handleSubmitTalKPrepare } from '../../service.js';

const TalkPreparation = ({ form, location }) => {
    const { query } = location;

    const { arrangeId = '', interviewRefCode = '', employeeCode = '' } = query;
    const { getFieldDecorator } = form;
    const [pageLoading, setPageLoading] = useState(false);
    const { data: interviewData = {}, loading: interviewLoading } = useRequest(() => getTalKPrepare(arrangeId), {
        ...defaultFormatResult
    });
    const {
        myQuestions = [],
        otherQuestions = [],
        interviewArrangeVO = {},
        dimissionOrderVO = {} // 离职单信息
    } = interviewData;
    const { interviewerEmployeeInfo = [] } = interviewArrangeVO;
    useEffect(() => {
        const { employeeCode: curEmployeeCode } = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : {};
        const isExist = interviewerEmployeeInfo.some(item => item.employeeCode === curEmployeeCode);
        if (interviewerEmployeeInfo.length && !isExist) {
            message.error('您不是当前面谈的面谈官！');
            history.goBack();
        }
    }, [interviewerEmployeeInfo]);

    const handleCancel = () => {
        pageTabUtil.goBack();
    };
    const handleSubmit = e => {
        e.preventDefault();
        form.validateFields({ force: true }, async (err, values) => {
            if (!err) {
                const { interviewQuestions = [] } = values;
                if (!interviewQuestions.length) {
                    message.error('自定义问题不能为空！');
                    return;
                }
                try {
                    setPageLoading(true);
                    const { msg, code } = await handleSubmitTalKPrepare({
                        dimissionCode: interviewRefCode,
                        arrangeId,
                        questionDTOList: interviewQuestions.map(item => ({
                            questionId: item.id,
                            question: item.question
                        }))
                    });
                    if (code === 10000) {
                        pageTabUtil.goBack();
                    } else {
                        message.error(msg);
                    }
                    setPageLoading(false);
                    // eslint-disable-next-line no-shadow
                } catch (e) {
                    console.log(e);
                }
            }
        });
    };
    const getInitialValue = () => myQuestions.length > 0 || otherQuestions.length > 0
            ? [
                ...myQuestions.map(x => ({
                    ...x,
                    question: x.title,
                    sort: 0,
                    edit: false,
                    quesType: 'self'
                })),
                ...otherQuestions.map(x => ({
                    ...x,
                    question: x.title,
                    sort: 0,
                    edit: false,
                    quesType: 'other' }))
            ]
            : [{ question: '', sort: '', edit: true, id: '', quesType: 'self' }];

    // 是否展示浏览态
    const disabled = useMemo(() => !(isEmpty(dimissionOrderVO) || dimissionOrderVO.dimissionStatus === 7),
        [dimissionOrderVO]);

    const bottomAction = useMemo(() => {
        if (isEmpty(interviewData) || disabled) {
            return null;
        }
        return (
            <BottomAction>
                <Button onClick={handleCancel} loading={pageLoading}>取消</Button>
                <Button type="primary" onClick={handleSubmit} loading={pageLoading}>
                    确定
                </Button>
            </BottomAction>
        );
    }, [disabled, handleSubmit, handleCancel, interviewData]);

    return (
        <PageContainer>
            <Spin spinning={pageLoading || interviewLoading}>
                <ProfileCard employeeCode={employeeCode}/>
                <TitleControl title="面谈安排">
                    <TalkArrange data={interviewArrangeVO} dimissionInfo={dimissionOrderVO}/>
                </TitleControl>
                <Form layout="inline">
                    <TitleControl title="面谈问题">
                        <Form.Item label="">
                            {getFieldDecorator('interviewQuestions', {
                                initialValue: getInitialValue(),
                                validateTrigger: 'onSubmit', // 设置进行表单验证的时机为onSubmit
                                rules: [
                                    {
                                        validator(_, value, callback) {
                                            console.log('自定义问题的校验数据', value);
                                            // eslint-disable-next-line no-restricted-syntax
                                            for (const item of value || []) {
                                                if (item.edit) {
                                                    callback('请完成自定义问题编辑！');
                                                    return;
                                                }
                                            }
                                            callback();
                                        }
                                    }
                                ]
                            })(<CustomAdd form={form} disabled={disabled} loading={interviewLoading} />)}
                        </Form.Item>
                    </TitleControl>
                </Form>
            </Spin>
            {bottomAction}
        </PageContainer>
    );
};

export default Form.create()(withRouter(TalkPreparation));
